import { TaskWrap } from "./task";
import type { Skill, Message, Task, AuthProvider, TaskEventWatch } from "./types";

export interface GuessSkillResponse {
    skillId: string;
}

export interface ListTaskResponse {
    totalCount: number;
    taskList: Task[];
}

export interface CreateTaskResponse {
    taskId: string;
}

export class SaApi {
    private apiSchema: "http" | "https";
    private apiHost: string;
    private authProvider: AuthProvider;

    constructor(apiSchema: "http" | "https", apiHost: string, authProvider: AuthProvider) {
        this.apiSchema = apiSchema;
        this.apiHost = apiHost;
        this.authProvider = authProvider;
    }

    private getApiUrl(subPath: string): string {
        return `${this.apiSchema}://${this.apiHost}/api/v1${subPath}`;
    }

    //列出所有技能
    async listSkill(): Promise<Skill[]> {
        const url = this.getApiUrl("/skills");
        const res = await fetch(url, {
            headers: this.authProvider.getAuthHeader(),
            method: "GET",
            mode: "cors",
        });
        if (res.status != 200) {
            const errNsg = await res.text();
            throw new Error(errNsg);
        }
        return res.json() as Promise<Skill[]>;
    }

    //根据用户输入选择技能
    async guessSkill(msg: Message): Promise<GuessSkillResponse> {
        const url = this.getApiUrl("/skill/guess");
        const res = await fetch(url, {
            body: JSON.stringify(msg),
            headers: {
                ...this.authProvider.getAuthHeader(),
                'Content-Type': 'application/json',
            },
            method: "POST",
            mode: "cors",
        })
        if (res.status != 200) {
            const errNsg = await res.text();
            throw new Error(errNsg);
        }
        return res.json() as Promise<GuessSkillResponse>;
    }

    //列出历史任务
    async listTask(offset: number, limit: number): Promise<ListTaskResponse> {
        const url = this.getApiUrl(`/tasks?offset=${offset}&limit=${limit}`);
        const res = await fetch(url, {
            headers: this.authProvider.getAuthHeader(),
            method: "GET",
            mode: "cors",
        });
        if (res.status != 200) {
            const errNsg = await res.text();
            throw new Error(errNsg);
        }
        return res.json() as Promise<ListTaskResponse>;
    }

    //新建任务
    async createTask(skillId: string, message: Message): Promise<CreateTaskResponse> {
        const url = this.getApiUrl("/task/create");
        const res = await fetch(url, {
            body: JSON.stringify({
                skillId,
                message,
            }),
            headers: {
                ...this.authProvider.getAuthHeader(),
                'Content-Type': 'application/json',
            },
            method: "POST",
            mode: "cors",
        })
        if (res.status != 200) {
            const errNsg = await res.text();
            throw new Error(errNsg);
        }
        return res.json() as Promise<CreateTaskResponse>;
    }

    //上传文件
    //formData里面只包含一个或多个文件
    async uploadFile(formData: FormData): Promise<string[]> {
        const url = this.getApiUrl("/file/upload");
        const res = await fetch(url, {
            body: formData,
            headers: this.authProvider.getAuthHeader(),
            method: "POST",
            mode: "cors",
        });
        if (res.status != 200) {
            const errNsg = await res.text();
            throw new Error(errNsg);
        }
        return res.json() as Promise<string[]>;
    }

    //获取任务代理对象
    getTaskWrap(taskId: string, eventWatch: TaskEventWatch): TaskWrap {
        return new TaskWrap(taskId, this.apiSchema, this.apiHost, this.authProvider, eventWatch);
    }
}